package khet.util;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;

public class OpenFileButton extends JButton implements
		DropTargetListener, ActionListener {

	private JFileChooser fileChooser;
	private OpenFileListener ofl;

	public OpenFileButton(String name, OpenFileListener ofl) {
		super(name);
		this.ofl = ofl;

		this.addActionListener(this);
		DropTarget dropTarget = new DropTarget(this, this);

		fileChooser = new JFileChooser();
	}

	private void openFile(File file) {
	    this.ofl.fileOpened(file);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (JFileChooser.APPROVE_OPTION == this.fileChooser.showOpenDialog(null))
		{ // TODO showOpenDialog could have frame as an argument
			File f = this.fileChooser.getSelectedFile();
			openFile(f);
		}
	}

	@Override
	public void dragEnter(DropTargetDragEvent arg0) {
	}

	@Override
	public void dragExit(DropTargetEvent arg0) {
	}

	@Override
	public void dragOver(DropTargetDragEvent arg0) {
	}

	@Override
	public void drop(DropTargetDropEvent arg0) {
		if (!arg0.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
			return;

		try {
			arg0.acceptDrop(DnDConstants.ACTION_LINK);
			Object o = arg0.getTransferable().getTransferData(
					DataFlavor.javaFileListFlavor);
			java.util.List<File> list = (java.util.List) o;
			for (File f : list) {
				openFile(f);
				break;
			}
		} catch (UnsupportedFlavorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void dropActionChanged(DropTargetDragEvent arg0) {
	}

}
